<template>
  <div class="realtime-monitor">
    <div class="monitor-header">
      <div class="header-left">
        <h1 class="page-title">实时监控大屏</h1>
        <a-space>
          <a-badge status="processing" text="实时更新中" />
          <span class="update-time">最后更新: {{ lastUpdateTime }}</span>
        </a-space>
      </div>
      <div class="header-right">
        <a-space>
          <a-button @click="toggleFullscreen">
            <FullscreenOutlined v-if="!isFullscreen" />
            <FullscreenExitOutlined v-else />
            {{ isFullscreen ? '退出全屏' : '全屏显示' }}
          </a-button>
          <a-button @click="toggleAutoRefresh">
            <PauseCircleOutlined v-if="autoRefresh" />
            <PlayCircleOutlined v-else />
            {{ autoRefresh ? '暂停刷新' : '开始刷新' }}
          </a-button>
          <a-select v-model:value="refreshInterval" style="width: 120px" @change="handleIntervalChange">
            <a-select-option :value="3000">3秒</a-select-option>
            <a-select-option :value="5000">5秒</a-select-option>
            <a-select-option :value="10000">10秒</a-select-option>
            <a-select-option :value="30000">30秒</a-select-option>
          </a-select>
        </a-space>
      </div>
    </div>

    <div class="monitor-content">
      <!-- 关键指标卡片 -->
      <a-row :gutter="[16, 16]">
        <a-col :xs="24" :sm="12" :lg="6">
          <a-card class="metric-card" :bordered="false">
            <a-statistic
              title="CPU 使用率"
              :value="metrics.cpu"
              suffix="%"
              :value-style="{ color: metrics.cpu > 80 ? '#f5222d' : '#3f8600' }"
            >
              <template #prefix>
                <DashboardOutlined />
              </template>
            </a-statistic>
            <div class="metric-trend">
              <a-progress
                :percent="metrics.cpu"
                :stroke-color="metrics.cpu > 80 ? '#f5222d' : '#52c41a'"
                :show-info="false"
              />
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <a-card class="metric-card" :bordered="false">
            <a-statistic
              title="内存使用率"
              :value="metrics.memory"
              suffix="%"
              :value-style="{ color: metrics.memory > 85 ? '#f5222d' : '#3f8600' }"
            >
              <template #prefix>
                <DatabaseOutlined />
              </template>
            </a-statistic>
            <div class="metric-trend">
              <a-progress
                :percent="metrics.memory"
                :stroke-color="metrics.memory > 85 ? '#f5222d' : '#52c41a'"
                :show-info="false"
              />
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <a-card class="metric-card" :bordered="false">
            <a-statistic
              title="活跃告警"
              :value="metrics.activeAlerts"
              :value-style="{ color: metrics.activeAlerts > 10 ? '#f5222d' : '#1890ff' }"
            >
              <template #prefix>
                <BellOutlined />
              </template>
            </a-statistic>
            <div class="metric-change">
              <ArrowUpOutlined style="color: #f5222d" />
              <span style="color: #f5222d; margin-left: 4px">+3 (1小时)</span>
            </div>
          </a-card>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <a-card class="metric-card" :bordered="false">
            <a-statistic
              title="待处理工单"
              :value="metrics.pendingTickets"
              :value-style="{ color: '#fa8c16' }"
            >
              <template #prefix>
                <FileTextOutlined />
              </template>
            </a-statistic>
            <div class="metric-change">
              <ArrowDownOutlined style="color: #52c41a" />
              <span style="color: #52c41a; margin-left: 4px">-2 (1小时)</span>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <!-- 图表区域 -->
      <a-row :gutter="[16, 16]" style="margin-top: 16px">
        <!-- CPU & 内存趋势图 -->
        <a-col :xs="24" :lg="12">
          <a-card title="系统资源趋势 (最近1小时)" :bordered="false" class="chart-card">
            <v-chart
              class="chart"
              :option="resourceChartOption"
              :autoresize="true"
            />
          </a-card>
        </a-col>

        <!-- 告警趋势图 -->
        <a-col :xs="24" :lg="12">
          <a-card title="告警趋势 (最近24小时)" :bordered="false" class="chart-card">
            <v-chart
              class="chart"
              :option="alertTrendOption"
              :autoresize="true"
            />
          </a-card>
        </a-col>

        <!-- 告警类型分布 -->
        <a-col :xs="24" :lg="8">
          <a-card title="告警类型分布" :bordered="false" class="chart-card">
            <v-chart
              class="chart"
              :option="alertTypeOption"
              :autoresize="true"
            />
          </a-card>
        </a-col>

        <!-- 告警级别分布 -->
        <a-col :xs="24" :lg="8">
          <a-card title="告警级别分布" :bordered="false" class="chart-card">
            <v-chart
              class="chart"
              :option="alertSeverityOption"
              :autoresize="true"
            />
          </a-card>
        </a-col>

        <!-- 服务健康状态 -->
        <a-col :xs="24" :lg="8">
          <a-card title="服务健康状态" :bordered="false" class="chart-card">
            <div class="service-status">
              <div
                v-for="service in services"
                :key="service.name"
                class="service-item"
              >
                <div class="service-info">
                  <a-badge
                    :status="service.status === 'healthy' ? 'success' : service.status === 'degraded' ? 'warning' : 'error'"
                  />
                  <span class="service-name">{{ service.name }}</span>
                </div>
                <div class="service-metrics">
                  <span class="metric-label">响应时间:</span>
                  <span class="metric-value">{{ service.responseTime }}ms</span>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>

        <!-- 网络流量 -->
        <a-col :xs="24" :lg="12">
          <a-card title="网络流量 (实时)" :bordered="false" class="chart-card">
            <v-chart
              class="chart"
              :option="networkChartOption"
              :autoresize="true"
            />
          </a-card>
        </a-col>

        <!-- 最近告警列表 -->
        <a-col :xs="24" :lg="12">
          <a-card title="最近告警" :bordered="false" class="chart-card">
            <a-list
              :data-source="recentAlerts"
              size="small"
              :pagination="false"
            >
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #avatar>
                      <a-badge
                        :status="getSeverityStatus(item.severity)"
                        :text="item.severity"
                      />
                    </template>
                    <template #title>
                      <span class="alert-title">{{ item.title }}</span>
                    </template>
                    <template #description>
                      <span class="alert-time">{{ formatTime(item.timestamp) }}</span>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  DashboardOutlined,
  DatabaseOutlined,
  BellOutlined,
  FileTextOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
])

interface Metrics {
  cpu: number
  memory: number
  activeAlerts: number
  pendingTickets: number
}

interface Alert {
  id: string
  title: string
  severity: 'critical' | 'high' | 'medium' | 'low'
  timestamp: string
}

interface Service {
  name: string
  status: 'healthy' | 'degraded' | 'unhealthy'
  responseTime: number
}

const metrics = reactive<Metrics>({
  cpu: 0,
  memory: 0,
  activeAlerts: 0,
  pendingTickets: 0,
})

const autoRefresh = ref(true)
const refreshInterval = ref(5000)
const isFullscreen = ref(false)
const lastUpdateTime = ref('')
let refreshTimer: number | null = null

const cpuHistory = ref<number[]>([])
const memoryHistory = ref<number[]>([])
const timeLabels = ref<string[]>([])

const services = ref<Service[]>([
  { name: 'API Gateway', status: 'healthy', responseTime: 45 },
  { name: 'Alert Service', status: 'healthy', responseTime: 32 },
  { name: 'Ticket Service', status: 'degraded', responseTime: 156 },
  { name: 'AI Service', status: 'healthy', responseTime: 89 },
  { name: 'Database', status: 'healthy', responseTime: 12 },
  { name: 'Redis Cache', status: 'healthy', responseTime: 3 },
])

const recentAlerts = ref<Alert[]>([
  {
    id: '1',
    title: 'CPU使用率超过90%',
    severity: 'critical',
    timestamp: new Date(Date.now() - 120000).toISOString(),
  },
  {
    id: '2',
    title: '磁盘空间不足',
    severity: 'high',
    timestamp: new Date(Date.now() - 300000).toISOString(),
  },
  {
    id: '3',
    title: 'API响应时间过长',
    severity: 'medium',
    timestamp: new Date(Date.now() - 600000).toISOString(),
  },
  {
    id: '4',
    title: '数据库连接池满',
    severity: 'high',
    timestamp: new Date(Date.now() - 900000).toISOString(),
  },
])

// 系统资源趋势图配置
const resourceChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
  },
  legend: {
    data: ['CPU使用率', '内存使用率'],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: timeLabels.value,
  },
  yAxis: {
    type: 'value',
    min: 0,
    max: 100,
    axisLabel: {
      formatter: '{value}%',
    },
  },
  series: [
    {
      name: 'CPU使用率',
      type: 'line',
      data: cpuHistory.value,
      smooth: true,
      itemStyle: {
        color: '#1890ff',
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
            { offset: 1, color: 'rgba(24, 144, 255, 0.05)' },
          ],
        },
      },
    },
    {
      name: '内存使用率',
      type: 'line',
      data: memoryHistory.value,
      smooth: true,
      itemStyle: {
        color: '#52c41a',
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(82, 196, 26, 0.3)' },
            { offset: 1, color: 'rgba(82, 196, 26, 0.05)' },
          ],
        },
      },
    },
  ],
}))

// 告警趋势图配置
const alertTrendOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
  },
  legend: {
    data: ['严重', '高', '中', '低'],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: Array.from({ length: 24 }, (_, i) => `${i}:00`),
  },
  yAxis: {
    type: 'value',
  },
  series: [
    {
      name: '严重',
      type: 'bar',
      stack: 'total',
      data: Array.from({ length: 24 }, () => Math.floor(Math.random() * 5)),
      itemStyle: { color: '#f5222d' },
    },
    {
      name: '高',
      type: 'bar',
      stack: 'total',
      data: Array.from({ length: 24 }, () => Math.floor(Math.random() * 10)),
      itemStyle: { color: '#fa8c16' },
    },
    {
      name: '中',
      type: 'bar',
      stack: 'total',
      data: Array.from({ length: 24 }, () => Math.floor(Math.random() * 15)),
      itemStyle: { color: '#fadb14' },
    },
    {
      name: '低',
      type: 'bar',
      stack: 'total',
      data: Array.from({ length: 24 }, () => Math.floor(Math.random() * 20)),
      itemStyle: { color: '#52c41a' },
    },
  ],
}))

// 告警类型分布
const alertTypeOption = computed(() => ({
  tooltip: {
    trigger: 'item',
  },
  legend: {
    orient: 'vertical',
    left: 'left',
  },
  series: [
    {
      name: '告警类型',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 35, name: '系统告警' },
        { value: 28, name: '应用告警' },
        { value: 20, name: '网络告警' },
        { value: 17, name: '数据库告警' },
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
    },
  ],
}))

// 告警级别分布
const alertSeverityOption = computed(() => ({
  tooltip: {
    trigger: 'item',
  },
  series: [
    {
      name: '告警级别',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2,
      },
      label: {
        show: true,
        position: 'outside',
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold',
        },
      },
      data: [
        { value: 12, name: '严重', itemStyle: { color: '#f5222d' } },
        { value: 25, name: '高', itemStyle: { color: '#fa8c16' } },
        { value: 38, name: '中', itemStyle: { color: '#fadb14' } },
        { value: 45, name: '低', itemStyle: { color: '#52c41a' } },
      ],
    },
  ],
}))

// 网络流量图
const networkChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
  },
  legend: {
    data: ['入站流量', '出站流量'],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: timeLabels.value,
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value} MB/s',
    },
  },
  series: [
    {
      name: '入站流量',
      type: 'line',
      data: Array.from({ length: timeLabels.value.length }, () =>
        (Math.random() * 50 + 20).toFixed(2)
      ),
      smooth: true,
      itemStyle: { color: '#1890ff' },
    },
    {
      name: '出站流量',
      type: 'line',
      data: Array.from({ length: timeLabels.value.length }, () =>
        (Math.random() * 40 + 15).toFixed(2)
      ),
      smooth: true,
      itemStyle: { color: '#52c41a' },
    },
  ],
}))

const loadMetrics = async () => {
  try {
    // TODO: Replace with actual API call
    metrics.cpu = Math.floor(Math.random() * 40 + 50)
    metrics.memory = Math.floor(Math.random() * 30 + 60)
    metrics.activeAlerts = Math.floor(Math.random() * 10 + 5)
    metrics.pendingTickets = Math.floor(Math.random() * 15 + 10)

    // Update history data
    const now = dayjs()
    cpuHistory.value.push(metrics.cpu)
    memoryHistory.value.push(metrics.memory)
    timeLabels.value.push(now.format('HH:mm:ss'))

    // Keep only last 20 data points
    if (cpuHistory.value.length > 20) {
      cpuHistory.value.shift()
      memoryHistory.value.shift()
      timeLabels.value.shift()
    }

    lastUpdateTime.value = now.format('HH:mm:ss')
  } catch (error) {
    console.error('Failed to load metrics:', error)
  }
}

const startAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  if (autoRefresh.value) {
    refreshTimer = window.setInterval(() => {
      loadMetrics()
    }, refreshInterval.value)
  }
}

const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value
  if (autoRefresh.value) {
    startAutoRefresh()
  } else if (refreshTimer) {
    clearInterval(refreshTimer)
  }
}

const handleIntervalChange = () => {
  if (autoRefresh.value) {
    startAutoRefresh()
  }
}

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
    isFullscreen.value = true
  } else if (document.exitFullscreen) {
    document.exitFullscreen()
    isFullscreen.value = false
  }
}

const getSeverityStatus = (severity: string) => {
  const statusMap: Record<string, any> = {
    critical: 'error',
    high: 'warning',
    medium: 'processing',
    low: 'default',
  }
  return statusMap[severity] || 'default'
}

const formatTime = (time: string) => {
  return dayjs(time).fromNow()
}

onMounted(() => {
  // Initialize with some data points
  for (let i = 0; i < 10; i++) {
    cpuHistory.value.push(Math.floor(Math.random() * 40 + 40))
    memoryHistory.value.push(Math.floor(Math.random() * 30 + 50))
    timeLabels.value.push(dayjs().subtract(10 - i, 'second').format('HH:mm:ss'))
  }

  loadMetrics()
  startAutoRefresh()
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped lang="scss">
.realtime-monitor {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;
}

.monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #f0f0f0;

  .page-title {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
  }

  .update-time {
    color: #8c8c8c;
    font-size: 12px;
  }
}

.monitor-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.metric-card {
  height: 100%;

  .metric-trend {
    margin-top: 16px;
  }

  .metric-change {
    margin-top: 8px;
    font-size: 12px;
  }
}

.chart-card {
  height: 100%;

  .chart {
    height: 300px;
    width: 100%;
  }
}

.service-status {
  .service-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .service-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .service-name {
        font-weight: 500;
      }
    }

    .service-metrics {
      .metric-label {
        color: #8c8c8c;
        font-size: 12px;
        margin-right: 4px;
      }

      .metric-value {
        font-weight: 500;
      }
    }
  }
}

.alert-title {
  font-weight: 500;
}

.alert-time {
  color: #8c8c8c;
  font-size: 12px;
}

:deep(.ant-statistic-title) {
  margin-bottom: 8px;
  color: #8c8c8c;
  font-size: 14px;
}

:deep(.ant-statistic-content) {
  font-size: 24px;
}
</style>
